﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Music.Utility.Helper
{
    /// <summary>
    /// 前后端加密一致算法
    /// </summary>
    public class CryptoJSHelper
    {
        /// <summary>
        /// KEY-16
        /// </summary>
        public static string key = "cloudin-eaforum1";

        /// <summary>
        /// IV-16
        /// </summary>
        public static string iv = "eaforum-cloudin2";

        /// <summary>
        /// CryptoJS 加密
        /// </summary>
        /// <param name="encStr"></param>
        /// <returns></returns>
        public static string Encrypt(string encStr)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(encStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// CryptoJS 解密
        /// </summary>
        /// <param name="decryptStr">base64加密字符串</param>
        /// <returns></returns>
        public static string Decrypt(string decryptStr)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = Convert.FromBase64String(decryptStr);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.Zeros;
            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}
